# -*- coding: utf-8 -*-
import json
from typing import Any, List

import requests
from loguru import logger


class Embeddings:
    def __init__(self, *args: Any, **kwargs: Any):
        self.online_embeddings_url = "http://60.205.246.174:8100/embedding"

    def embed_documents(self, texts: List[str]) -> List[List[float]]:
        try:    
            response = requests.post(self.online_embeddings_url, json={"texts": texts})
            response.raise_for_status()
            return response.json()["embeddings"]
        except Exception as e:
            logger.error(f"Embedding failed: {e}")
            raise


    def embed_query(self, text: str) -> List[float]:
        return self.embed_documents([text])[0]


class EmbeddingsServer:
    def __init__(self, *args: Any, **kwargs: Any):
        self.online_rerank_url = "http://10.168.20.20:5001/v1/embeddings"
        self.API_KEY = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4ZDJkZDdiM2FhZDE0ZDU5YjI0OTZjMzc0MTNiMjJkZiIsIm1ldGhvZHMiOiJQT1NUIiwiaWF0IjoiMTc0OTE3ODAzNCIsImV4cCI6IjE3NDkxODE2MzQifQ.CzQz52w5lhYi6fGYBKwSU0N_cZ3OKydwhqs8_mrVIxtoqjIO2ZZpnNbj96JT_CYRQxajo03jD2DJX8FgoD0WjE8vIdys_Gva4nY4mIwxYpGjyta-zJKEJ9qK3R0ihJ9YCf0EgAiwIu5dAnFso4tHZ4Kw-aQ-bNMZRCBNEcVMfAQxftcmMxOB4vjQPU96aZjOYmgge10rE-HOC-qd2BfF8Jh3poeeTjM4KD6pedLSqoaWhn-6P5RIs1KVRElMAE7OkvQzVDZPviHKTvvjq3RyIQbFIsXJw3RdHgTCH6-yca3Dhm5xs0m6HoXvj2Dn1UOXu0wegb5C1Q_AxBjFalwFIQ"

    def embed_query(self, text: str) -> List[float]:
        try:
            headers = {
                "Authorization": f"Bearer {self.API_KEY}",
                "Content-Type": "application/json"
            }
            payload = {
                "model": "bge-m3",
                "input": text,
                "encoding_format": "float",
            }
            response = requests.post(self.online_rerank_url, data=json.dumps(payload), headers=headers).json()
            return response["data"][0]["embedding"]
        except Exception as e:
            logger.error(f"Embeddings failed: {e}")
            raise
    
    def embed_documents(self, texts: List[str]) -> List[List[float]]:
        embeddings = []
        for text in texts:
            embeddings.append(self.embed_query(text))
        return embeddings
